<template>
  <div class="min-h-screen bg-gray-50">
    <div class="max-w-7xl mx-auto px-4 py-8">
      <div class="grid grid-cols-1 gap-8">
        <div class="col-span-3">
          <div class="bg-white p-6 rounded-lg shadow-md mb-8">
            <div class="flex items-center space-x-4 mb-6">
              <div class="w-20 h-20 rounded-full bg-gray-200 flex items-center justify-center">
                <i class="fas fa-user text-4xl text-gray-400"></i>
              </div>
              <div>
                <h2 class="text-xl font-medium">{{ userName }}</h2>
              </div>
            </div>
            <div class="grid grid-cols-2 gap-4 mb-6">
              <div class="bg-gray-50 p-4 rounded-lg text-center">
                <div class="text-2xl font-medium text-custom">{{ sub_days }}</div>
                <div class="text-sm text-gray-500">累計学習日数</div>
              </div>
              <div class="bg-gray-50 p-4 rounded-lg text-center">
                <div class="text-2xl font-medium text-custom">{{ answer_sums }}</div>
                <div class="text-sm text-gray-500">解答数</div>
              </div>
            </div>
            <div class="grid grid-cols-4 gap-4">
              <div class="bg-white p-4 rounded-lg shadow hover:shadow-md transition-shadow">
                <div class="text-2xl font-medium text-custom mb-2">{{ mouth_info }}</div>
                <div class="text-sm text-gray-500">今月の完了した問題</div>
              </div>

              <div class="bg-white p-4 rounded-lg shadow hover:shadow-md transition-shadow">
                <div class="text-2xl font-medium text-custom mb-2">{{ success_rate }}%</div>
                <div class="text-sm text-gray-500">練習の正答率</div>
              </div>
              <!-- <div class="bg-white p-4 rounded-lg shadow hover:shadow-md transition-shadow">
                <div class="text-2xl font-medium text-custom mb-2">{{ roundMinutes(scorce_sum) }}{{
                  isMinuteOrHour(roundMinutes(scorce_sum)) }}</div>
                <div class="text-sm text-gray-500">総学習時間</div>
              </div> -->
            </div>
          </div>
          <div>
            <div class="bg-white p-4 rounded-lg shadow-sm hover:shadow-md transition-shadow">
              <div class="flex items-center justify-between mb-4">
                <h3 class="font-medium">成績統計</h3>
              </div>
              <div class="serch_div">
                <el-date-picker v-model="value2" type="daterange" align="right" unlink-panels @change="update_change"
                locale="ja"
                value-format="yyyy-MM-dd"
                 @input="handleDateChange"
                  range-separator="~" start-placeholder="開始日" end-placeholder="終了日" :picker-options="pickerOptions">
                </el-date-picker>
              </div>
              <el-table :data="lis" empty-text="データなし">
                <el-table-column align="center" label="番号" width="400">
                  <template slot-scope="scope">
                    {{ scope.$index + 1 }}
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="category_name" label="カテゴリー" width="400">
                </el-table-column>

                <el-table-column align="center" prop="source" label="得点" width="100">
                </el-table-column>
                <el-table-column align="center" prop="address" label="操作">
                  <template slot-scope="scope">
                    <el-button type="primary" @click="viewDetail(scope.row)">詳細</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="page_div">
                <el-pagination @current-change="handleChange" :current-page.sync="currentPage" background
                  :page-size.sync="pageSize" :total="total" :page-sizes="[10, 20, 30, 40]" layout="prev, pager, next" />
              </div>


            </div>

          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

import { post, get } from "@/http/axios";
export default {
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近1週間',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近1ヶ月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近3ヶ月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      value2: '',
      activeName: 'first',
      userName: "",
      sub_days: "",
      answer_sums: "",
      total: 0,
      pageSize: 10,
      currentPage: 1,
      chartRef: null,
      chartRefSource: null,
      mouth_info: "",
      start_date: "",
      end_date: "",
      success_rate: "",
      lis: [],
      scorce_sum: "",
      categories: [],
      weekDays_en: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
      weekDays: ['月', '火', '水', '木', '金', '土', '日'], // 曜日
      seriesData: [] // 存储 ECharts 数据
    };
  },
  async mounted() {
    this.chartRef = this.$refs.chartRef;
    this.chartRefSource = this.$refs.chartRefSource;
    const loading = this.$loading({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    await this.getUserInfo();
    await this.getSubDay();
    await this.getAnswerSum();
    await this.getMouthInfo();
    await this.sum_success_rate();
    await this.getData(1)
    loading.close()

  },
  methods: {
    async update_change(e) {
      if(e){
        this.start_date = e[0]
        this.end_date = e[1]
      }else{
        this.start_date=""
        this.end_date=""
      }

      this.getData(this.currentPage)

    },
    async handleChange(val) {
      await this.getData(val)
    },
    handleDateChange(val) {
      if (val === '') {
        console.log('Date cleared');
        // 这里可以执行清除事件的逻辑
      }
    },
    viewDetail(row) {
      this.$router.push({ path: "/suceesView", query: { branch_id: row.branch_id } })
    },
    async getData(pageNum) {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      let url=""
      if(this.start_date){
        url = `/get_category_scores?current_page=${pageNum}&start_date=${this.start_date}&end_date=${this.end_date}`
      }else{
        url = `/get_category_scores?current_page=${pageNum}`
      }
      let data = await get(url)
      loading.close()
      this.lis = data.data.data.list
      this.total = data.data.data.paginator.total_record
      this.currentPage = data.data.data.paginator.current_page
    },
    async handleClick(tab, event) {
      if (tab.index == 0) {
        await this.loadChartData();
      } else {
        await this.loadChardDate();
      }
    },

    async getSubDay() {
      let data = await get("/study_days");
      this.sub_days = data.data.data;
    },
    async getAnswerSum() {
      let data = await get("/answer_sum");
      this.answer_sums = data.data.data;
    },
    async getMouthInfo() {
      let data = await get("/get_moth_count");
      this.mouth_info = data.data.data;
    },
    async sum_success_rate() {
      let data = await get("/sum_success_rate");
      this.success_rate = data.data.data;
    },
    async getScoreSum() {
      let data = await get("/getScoreSum");
      this.scorce_sum = data.data.data;
    },
    async getUserInfo() {
      let data = await post("/getuser_info");
      this.userName = data.data.data.user_name;
    },
    roundMinutes(minutes) {
      return Math.round(minutes);
    },
    isMinuteOrHour(value) {
      // 处理负数和非整数情况
      if (value < 0 || !Number.isInteger(value)) {
        return '无效的输入，请输入一个非负整数';
      }

      // 处理分钟
      if (value >= 0 && value < 60) {
        return '分钟';
      }

      // 处理小时，包括超过23小时但小于48小时的情况
      if (value >= 0 && value <= 23) {
        return '小时';
      } else if (value > 23 && value <= 47) {
        // 将超过24小时但小于48小时的值转换为0-23的范围
        value = value - 24;
        return '小时';
      } else if (value > 47 && value <= 71) {
        value = value - 48;
        return '小时';
      } else {
        return '无效的分钟或小时值';
      }
    },
    isMinuteOrHour(value) {
      // 处理负数和非整数情况
      if (value < 0 || !Number.isInteger(value)) {
        return '无效的输入，请输入一个非负整数';
      }

      // 处理分钟
      if (value >= 0 && value < 60) {
        return '分钟';
      }

      // 处理小时，包括超过23小时但小于48小时的情况
      if (value >= 0 && value <= 23) {
        return '小时';
      } else if (value > 23 && value <= 47) {
        // 将超过24小时但小于48小时的值转换为0-23的范围
        value = value - 24;
        return '小时';
      } else if (value > 47 && value <= 71) {
        value = value - 48;
        return '小时';
      } else {
        return '无效的分钟或小时值';
      }
    },
  }
};
</script>

<style scoped>
.text-custom {
  color: #000000;
}

.bg-custom {
  background-color: #000000;
}

.page_div {
  width: 100%;
  margin-top: .5rem;
  display: flex;
  justify-content: center;
}
</style>
